package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.RoleConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.entity.Message;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.service.MessageService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.Sincerity;
import com.ibeetl.cms.entity.Site;
import com.ibeetl.cms.entity.SiteFunds;
import com.ibeetl.cms.entity.StateTable;
import com.ibeetl.cms.service.*;
import com.ibeetl.cms.util.BusinessTypeConstant;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.util.RoleConstant;
import com.ibeetl.cms.web.query.SiteFundsQuery;
import com.ibeetl.cms.web.query2.SiteFundsEnterpriseQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * SiteFunds 接口
 */
@Controller
public class SiteFundsController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/siteFunds";


    @Autowired private SiteFundsService siteFundsService;

    @Autowired
    FileService fileService;

    @Autowired
    CorePlatformService platformService;

    @Autowired private EnterpriseService enterpriseService;

    @Autowired
    private EssentialInformationService essentialInformationService;

    @Autowired
    private RoleConsoleService roleConsoleService;

    @Autowired
    private  SincerityService sincerityService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private BusinessProcessService businessProcessService;

    private StateTable stateTable=new StateTable();
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("siteFunds")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/siteFunds/index.html") ;
        view.addObject("search", SiteFundsQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/chushenindex.do")
    @Function("siteFunds.check")
    @ResponseBody
    public ModelAndView chushenindex() {
        ModelAndView  view  = new ModelAndView("/cms/siteFunds/chushenindex.html");
        view.addObject("search", SiteFundsEnterpriseQuery.class.getName());
            return view;
    }

    @GetMapping(MODEL + "/fushenindex.do")
    @Function("siteFunds.review")
    @ResponseBody
    public ModelAndView fushenindex() {
        ModelAndView  view = new ModelAndView("/cms/siteFunds/fushenindex.html");
        view.addObject("search", SiteFundsEnterpriseQuery.class.getName());
        return view;
    }


    @GetMapping(MODEL + "/shenhe.do")
    @ResponseBody
    public ModelAndView shenhe(Integer id, String roleName) {
        ModelAndView view;
        if(roleName.equals("chushen")){
            view = new ModelAndView("/cms/siteFunds/chushenedit.html");
        }else {//复审
            view = new ModelAndView("/cms/siteFunds/fushenedit.html");
        }
        List<Site> lists=siteFundsService.getSite();
        view.addObject("companies", lists);
        SiteFunds siteFunds = siteFundsService.queryById(id);
        siteFunds.setRoleName(roleName);
        view.addObject("siteFunds", siteFunds);
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("siteFunds")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/siteFunds/edit.html");
        SiteFunds siteFunds = siteFundsService.queryById(id);

        List<Site> lists=siteFundsService.getSite();
        view.addObject("companies", lists);
        view.addObject("siteFunds", siteFunds);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("siteFunds")
    @ResponseBody
    public ModelAndView add() {
        CoreUser currentUser = platformService.getCurrentUser();
        ModelAndView view = new ModelAndView("/cms/siteFunds/add.html");
        view.addObject("unitName", currentUser.getName());
        return view;
    }

    //查询站点名称
    @PostMapping(MODEL + "/getSite.do")
    //@Function("siteFunds")
    @ResponseBody
    public List<Site> getSite(){
        return siteFundsService.getSite();
    }

    //根据id搜索站点信息
    @PostMapping(MODEL + "/findSite.do")
   // @Function("siteFunds")
    @ResponseBody
    public Site findSite(Integer id){
        return siteFundsService.findSite(id);
    }


    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("siteFunds")
    @ResponseBody
    public JsonResult<PageQuery> list(SiteFundsQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        if(null == condtion.getYear()){
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            String yearStr = year.toString();
            condtion.setYear(yearStr);
        }
        condtion.setCompanyId(getUserId().intValue());
        //查询数据
        siteFundsService.querydata(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/chushenlist.json")
    @Function("siteFunds.check")
    @ResponseBody
    public JsonResult<PageQuery> chushenlist(SiteFundsQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        condtion.setYear(yearStr);
        condtion.setBusinessState(ProcessConstant.TO_FIRSTCHECK);
            //查询数据
            siteFundsService.queryExamine(page);
        return JsonResult.success(page);
    }
    @PostMapping(MODEL + "/fushenlist.json")
    @Function("siteFunds.review")
    @ResponseBody
    public JsonResult<PageQuery> fushenlist(SiteFundsQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        condtion.setYear(yearStr);
            condtion.setBusinessState(ProcessConstant.TO_FINALCHECK);
            //查询数据
            siteFundsService.queryExamine(page);
        return JsonResult.success(page);
    }


    /**
     * 新增（保存）
     *
     * @param siteFunds
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("siteFunds")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)SiteFunds siteFunds)
    {
        CoreUser user = platformService.getCurrentUser();
        Long userId = user.getId();
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        siteFunds.setYear(yearStr);
        siteFunds.setUserId(userId.intValue());
        siteFunds.setCreationDate(new Date());
        siteFunds.setCompanyId(Math.toIntExact(user.getId()));

        siteFunds.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);
        siteFundsService.save(siteFunds);

        //调用增加业务流程数据
        businessProcessService.processInformation(siteFunds.getId(),siteFunds.getBusinessState(),
                siteFunds.getBusinessStateCode(),siteFunds.getHandlingSuggestion(),"成功", BusinessTypeConstant.siteFunds);
        return new JsonResult().success();
    }

    /**
     * 新增（保存并申请）
     *
     * @param siteFunds
     * @return
     */
    @PostMapping(MODEL + "/savedeclaration.json")
    @Function("siteFunds")
    @ResponseBody
    public JsonResult savedeclaration(@Validated(ValidateConfig.ADD.class) SiteFunds siteFunds) {
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        siteFunds.setYear(yearStr);
        CoreUser user = platformService.getCurrentUser();
        siteFunds.setUserId(user.getId().intValue());
        siteFunds.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        siteFunds.setCreationDate(new Date());
        siteFunds.setDateReporting(new Date());
        siteFunds.setCompanyId(Math.toIntExact(user.getId()));
        siteFundsService.save(siteFunds);

        //调用增加业务流程数据
        businessProcessService.processInformation(siteFunds.getId(),siteFunds.getBusinessState(),
                siteFunds.getBusinessStateCode(),siteFunds.getHandlingSuggestion(),"成功", BusinessTypeConstant.siteFunds);
        return new JsonResult().success();
    }

    /**
     * 修改（保存）
     * @param siteFunds
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("siteFunds")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  SiteFunds siteFunds) {
        siteFunds.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);
        boolean success = siteFundsService.updateTemplate(siteFunds);

        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 修改（保存并申请）
     *
     * @param siteFunds
     * @return
     */
    @PostMapping(MODEL + "/editandsave.json")
    @Function("siteFunds")
    @ResponseBody
    public JsonResult<String> editandsave(@Validated(ValidateConfig.UPDATE.class)  SiteFunds siteFunds) {
        siteFunds.setDateReporting(new Date());

        siteFunds.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);

        boolean success = siteFundsService.updateTemplate(siteFunds);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }




    @GetMapping(MODEL + "/view.json")
    @Function("siteFunds")
    @ResponseBody
    public JsonResult<SiteFunds>queryInfo(Integer id) {
        SiteFunds siteFunds = siteFundsService.queryById( id);
        return  JsonResult.success(siteFunds);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("siteFunds")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        siteFundsService.batchDelSiteFunds(idList);
        return new JsonResult().success();
    }
    /**
     * 查看页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/findenterprise.do")
    @ResponseBody
    public ModelAndView findenterprise(Integer id) {
        ModelAndView view = new ModelAndView("/cms/siteFunds/findenterpriseedit.html");
        SiteFunds siteFunds = siteFundsService.queryById(id);
        List<Site> lists=siteFundsService.getSite();
        view.addObject("look",true);
        view.addObject("companies", lists);
        view.addObject("siteFunds", siteFunds);
        return view;
    }

    @PostMapping(MODEL + "/firstcheckList.json")
    @ResponseBody
    public JsonResult<PageQuery> firstcheckList(SiteFundsQuery condtion) {
        /**
         * 获得本年度已办任务
         */
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        condtion.setYear(year.toString());

        condtion.setProcessUserId(getUserId());
        condtion.setBusinessType(BusinessTypeConstant.siteFunds);
        PageQuery page = condtion.getPageQuery();
        siteFundsService.queryDoneTask(page);
        return JsonResult.success(page);
    }


    /**
     * 初审终止
     */
    @PostMapping(MODEL + "/FirstTrialTermination.json")
    @Function("siteFunds.check")
    @ResponseBody
    public JsonResult<String> FirstTrialTermination(@Validated(ValidateConfig.UPDATE.class) SiteFunds siteFunds) {
        siteFunds.setBusinessState(ProcessConstant.TERMINIATE_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.TERMINIATE);
        siteFunds.setProcessResult(ProcessConstant.FIRSTCHECK_TERMINIATE_STR);
        boolean success = siteFundsService.updateTemplate(siteFunds);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(siteFunds.getId(),ProcessConstant.TERMINIATE_STR,
                    ProcessConstant.TERMINIATE,siteFunds.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_TERMINIATE_STR,BusinessTypeConstant.siteFunds);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审终止
     */
    @PostMapping(MODEL + "/RetrialTermination.json")
    @Function("siteFunds.review")
    @ResponseBody
    public JsonResult<String> RetrialTermination(@Validated(ValidateConfig.UPDATE.class) SiteFunds siteFunds) {
        siteFunds.setBusinessState(ProcessConstant.TERMINIATE_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.TERMINIATE);
        siteFunds.setProcessResult(ProcessConstant.FINALCHECK_TERMINIATE_STR);
        boolean success = siteFundsService.updateTemplate(siteFunds);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(siteFunds.getId(),ProcessConstant.TERMINIATE_STR,
                    ProcessConstant.TERMINIATE,siteFunds.getHandlingSuggestion(),ProcessConstant.FINALCHECK_TERMINIATE_STR,BusinessTypeConstant.siteFunds);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 初审退回
     */
    @PostMapping(MODEL + "/initialReview.json")
    @Function("siteFunds.check")
    @ResponseBody
    public JsonResult<String> initialReview(@Validated(ValidateConfig.UPDATE.class) SiteFunds siteFunds) {
        siteFunds.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        siteFunds.setProcessResult(ProcessConstant.FIRSTCHECK_STR);
        boolean success = siteFundsService.updateTemplate(siteFunds);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(siteFunds.getId(),ProcessConstant.FIRSTCHECK_STR,
                    ProcessConstant.FIRSTCHECK,siteFunds.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_STR,BusinessTypeConstant.siteFunds);
            //给企业发一条退回信息
            Message message=new Message();
            message.setCompanyId(siteFunds.getCompanyId());
            message.setUserId(siteFunds.getUserId());
            message.setStatus(-1);
            message.setContent(siteFunds.getHandlingSuggestion());
            message.setType(Integer.parseInt(BusinessTypeConstant.siteFunds));
            message.setCreateDate(new Date());
            messageService.save(message);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审退回
     */
    @PostMapping(MODEL + "/Reexamination.json")
    @Function("siteFunds.review")
    @ResponseBody
    public JsonResult<String> Reexamination(@Validated(ValidateConfig.UPDATE.class) SiteFunds siteFunds) {
        siteFunds.setBusinessState(ProcessConstant.TO_FIRSTCHECK_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.TO_FIRSTCHECK);
        siteFunds.setProcessResult(ProcessConstant.FINALCHECK_BACK_STR);
        boolean success = siteFundsService.updateTemplate(siteFunds);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(siteFunds.getId(),ProcessConstant.FINALCHECK_BACK_STR,
                    ProcessConstant.FINALCHECK_BACK,siteFunds.getHandlingSuggestion(),ProcessConstant.FINALCHECK_BACK_STR,BusinessTypeConstant.siteFunds);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 初审通过
     */
    @PostMapping(MODEL + "/FirstTrial.json")
    @Function("siteFunds.check")
    @ResponseBody
    public JsonResult<String> FirstTrial(@Validated(ValidateConfig.UPDATE.class) SiteFunds siteFunds) {
        String businessType = "10";
        List<Sincerity> sincerityList = sincerityService.blacklist(siteFunds.getUserId(), siteFunds.getCompanyId(), businessType);
        if (null != sincerityList && sincerityList.size() > 0) {
            //用户或用户所属企业已进入黑名单
            for (Sincerity sincerity : sincerityList) {
                if (sincerity.getType().equals(Long.toString(RoleConstant.COMPANY))) {
                    //企业
                    String name = enterpriseService.findenterprise(siteFunds.getCompanyId()).getEnterpriseName();
                    return JsonResult.failMessage(name + "公司在黑名单中有记录");
                }
            }
        }

        siteFunds.setProcessResult(ProcessConstant.FIRSTCHECK_ADOPT_STR);
        siteFunds.setBusinessState(ProcessConstant.TO_FINALCHECK_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.TO_FINALCHECK);
        boolean success = siteFundsService.updateTemplate(siteFunds);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(siteFunds.getId(),ProcessConstant.FIRSTCHECK_ADOPT_STR,
                    ProcessConstant.FIRSTCHECK_ADOPT,siteFunds.getHandlingSuggestion(),ProcessConstant.FIRSTCHECK_ADOPT_STR,BusinessTypeConstant.siteFunds);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 复审通过
     */
    @PostMapping(MODEL + "/ReviewThrough.json")
    @Function("siteFunds.review")
    @ResponseBody
    public JsonResult<String> ReviewThrough(@Validated(ValidateConfig.UPDATE.class) SiteFunds siteFunds) {
        siteFunds.setProcessResult(ProcessConstant.FINALCHECK_ADOPT_STR);
        siteFunds.setBusinessState(ProcessConstant.DONE_STR);
        siteFunds.setBusinessStateCode(ProcessConstant.DONE);
        boolean success = siteFundsService.updateTemplate(siteFunds);
        if (success) {
            //调用增加业务流程数据
            businessProcessService.processInformation(siteFunds.getId(),ProcessConstant.FINALCHECK_ADOPT_STR,
                    ProcessConstant.FINALCHECK_ADOPT,siteFunds.getHandlingSuggestion(),ProcessConstant.FINALCHECK_ADOPT_STR,BusinessTypeConstant.siteFunds);
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }

    }


// 人才公共方法(所有)

    /**
     * 公共方法
     * 用于获取登录ID
     *
     * @return
     */
    public Long getUserId() {
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        return userId;
    }
}
